package behaviors;

import model.Assets;
import model.Entity;

import org.jbox2d.common.MathUtils;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.ContactPoint;
import org.jbox2d.dynamics.contacts.ContactResult;

public class Bullet extends Behavior {
	public Entity shapeData1, shapeData2;

	@Override
	public void onCollide(ContactPoint arg0) {
		shapeData1 = ((Entity) arg0.shape1.getBody().getUserData());
		shapeData2 = ((Entity) arg0.shape2.getBody().getUserData());

		// if bullet hits itself, then kill it immediately
		// TODO implement delayed destruction for high end systems
		// if (shapeData1.isBullet && shapeData2.isBullet) {
		// shapeData1.recycle = true;
		// shapeData2.recycle = true;
		// }
		
		if (shapeData1.isBullet && !shapeData2.isSensor) {
			shapeData1.recycle = true;
		}
		if (shapeData2.isBullet && !shapeData1.isSensor) {
			shapeData2.recycle = true;
		}
		
		// play bullet ricochet sound
		if (shapeData1.isBullet || shapeData2.isBullet) {
			Assets.getInstance().getSound("assets/sfx/dink.wav").play();
		}
	}

	@Override
	public void onRemove(ContactPoint arg0) {
	}

	@Override
	public void onPersist(ContactPoint arg0) {
	}

	@Override
	public void onResult(ContactResult arg0) {
	}

	@Override
	public void update(Body b) {
		super.update(b);

		if (body.isBullet()) {
			float angle = MathUtils.atan2(-body.getLinearVelocity().x, body
					.getLinearVelocity().y);
			body.setXForm(body.getPosition(), (float) (angle + (Math.PI / 2)));
		}
	}

	@Override
	public void init() {
	}
}
